<template>
  <page-container title="角色管理">
    <!-- 表单区域 -->
    <el-form inline>
      <el-form-item label="搜索:">
        <el-input style="width: 240px" placeholder="角色名称" v-model="parameter.roleName"/>
      </el-form-item>

      <el-form-item label="状态:">
        <el-select v-model="parameter.status" placeholder="状态" style="width: 240px" @change="onSearch">
          <el-option v-for="(item, index) in options" :key="index" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="selectClick">查询</el-button>
        <el-button type="success" plain @click="add">新增</el-button>
        <el-popconfirm title="确定删除吗?"
                       confirm-button-text="确定"
                       cancel-button-text="取消"
                       @Confirm="delByIds">
          <template #reference>
            <el-button type="danger" plain>批量删除</el-button>
          </template>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <div style="text-align:right"></div>

    <!-- -----------------表格---------------- -->
    <el-table :data="filterTableData"
              border size="large"
              row-key="managerId"
              style="width: 100%"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" fixed/>
      <el-table-column label="角色名称" prop="roleName" width="120"/>
      <el-table-column label="权限字符" prop="roleKey" width="120" show-overflow-tooltip/>
      <el-table-column label="显示顺序" prop="roleSort" width="120" show-overflow-tooltip/>
      <el-table-column label="状态" prop="status" width="120" show-overflow-tooltip>
        <template  v-slot="scope">
          <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              class="mt-2"
              style="margin-left: 24px"
              inline-prompt
              :active-icon="Check"
              :inactive-icon="Close"
              @change="updateStatus($event,scope.row.roleId,scope.row.status)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="120" show-overflow-tooltip/>
      <el-table-column label="备注" prop="remark" show-overflow-tooltip/>

      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button circle plain type="primary" @click="onUpdate(scope.row.roleId)" :icon="Edit"></el-button>

          <el-popconfirm title="确定删除吗?"
                         confirm-button-text="确定"
                         cancel-button-text="取消"
                         @Confirm="del(scope.row.roleId)">
            <template #reference>
              <el-button circle plain type="danger" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination background layout="->,prev, pager, next"
                   :total="paginations.total"
                   @change="tableChange"/>

    <RoleSave v-model:model-value="modelValue"
              v-model:form="form"
              v-model:menuPerm="menuPerm"
              v-model:title="title"
              @search="onSearch()"
              ref="childRef"></RoleSave>
  </page-container>
</template>


<script setup>
import {ref, computed} from 'vue'
import {Check, Close, Delete, Edit} from "@element-plus/icons-vue";
import {usePagination, useRequest} from 'vue-request'
import {changeStatusById, deleteByIds, pageList, selectRoleById} from '@/api/sys/role.js'
import PageContainer from "@/components/PageContainer.vue";
import RoleSave from "@/components/sys/role/RoleSave.vue";
import {handleTree} from "@/utils/sg.js";
import {ElMessage} from "element-plus";


//子组件参数
const modelValue = ref(false)

const title = ref(false)

const childRef = ref()

// form表单参数
const form = ref({
  roleId: undefined,
  roleName: '',
  roleKey: '',
  roleSort: 1,
  status: '',
  menuIds: [],
  remark: '',
  checkedKeys: []
})

//菜单列表
const menuPerm = ref({
  menuExpand: false,
  menuNodeAll: false,
})

// 表单重置
function reset() {
  // eslint-disable-next-line no-sequences
  (menuPerm.value.menuNodeAll = false),
      (menuPerm.value.menuExpand = false),
      (form.value = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: '0',
        menuIds: [],
        remark: undefined,
        checkedKeys: []
      })

}

//新增按钮
function add() {
  modelValue.value = true
  title.value = true
  reset()
}


//修改
async function onUpdate(id) {
  this.reset()
  modelValue.value = true
  title.value = false
  await selectRoleById(id).then((res) => {
    if (res?.data.code === 200) {
      form.value = res?.data.data
      childRef.value.echo(form.value.checkedKeys)
    }
  })
}


//==================================================

//查询参数
const parameter = ref({
  page: 1,
  size: 5,
  status: '0',
  roleName: '',
  roleKey:'',
})


//分页查询
const {data, total, run: search} = usePagination((d) => pageList(d), {
  defaultParams: [parameter.value],
  pagination: {
    currentKey: 'page',
    pageSizeKey: 'size',
    totalKey: 'data.data.count',
  }
})

//分页数据计算属性
const paginations = computed(() => {
  return {
    current: parameter.value?.page, //当前页
    pageSize: parameter.value?.size, //页大小
    total: total.value,
  }
})


const options = [
  {
    value: '0',
    label: '启用',
  },
  {
    value: '1',
    label: '禁用',
  },
]

//角色数据计算属性
const filterTableData = computed(() => {
  console.log(data.value?.data.data?.results);
  
  return data.value?.data.data?.results || []
})

function onSearch() {
  search(parameter.value)
}

//分页事件
function tableChange(currentPage, pageSize) {
  parameter.value.page = currentPage ?? 1
  parameter.value.size = pageSize ?? 10
  search(parameter.value)
}

//查询点击
function selectClick() {
  search(parameter.value)
}

//批量删除/单个删除
const ids = ref([])
const {run: deleteById} = useRequest((ids) => deleteByIds(ids),
    {
      manual: true
    }
)

async function del(id) {
  ids.value.push(id)
  await deleteById(ids.value).then((res)=>{
    search(parameter.value)
  })

  
}

//收集选中的id
function handleSelectionChange(val) {
  ids.value = []
  val.forEach(po => {
    ids.value.push(po.roleId)
  })
}

//批量删除
async function delByIds() {
  await deleteById(ids.value).then((res)=>{
    search(parameter.value)
  })
}


const {runAsync: updateStatusById} = useRequest((d) => changeStatusById(d),
    {
      manual: true
    }
)

//修改状态
async function updateStatus(on,id, status) {
  if (on){
    await updateStatusById({id, status}).then((res) => {
      if (res?.data.code !== 200) {
        //修改失败
        filterTableData.value.status = !filterTableData.value.status
        ElMessage.error('修改失败，请重试！')
      }else {
        ElMessage({
          message: '修改成功！',
          type: 'success',
        })
        onSearch(parameter.value)
      }
    })
  }
}


</script>

<style scoped>

</style>